<template>
  <div class="http-voice-chat">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <div class="service-indicator">
        <div :class="['status-dot', serviceStatus]"></div>
        <span class="status-text">{{ serviceStatusText }}</span>
      </div>
      <div class="mode-toggle">
        <button 
          :class="['mode-btn', { active: !isVoiceMode }]"
          @click="setMode(false)"
        >
          💬 文本
        </button>
        <button 
          :class="['mode-btn', { active: isVoiceMode }]"
          @click="setMode(true)"
        >
          🎤 语音
        </button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area" ref="chatArea">
      <div class="messages-container">
        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="ai-avatar">🤖</div>
          <div class="welcome-text">
            <h3>AI语音助手已启动，选择文本或语音模式开始对话</h3>
            <p>{{ isVoiceMode ? '点击麦克风开始语音对话' : '在下方输入框开始文字对话' }}</p>
          </div>
        </div>

        <!-- 消息列表 -->
        <div
          v-for="message in messages"
          :key="message.id"
          :class="['message-item', message.type]"
        >
          <div class="message-avatar">
            {{ message.type === 'user' ? '👤' : '🤖' }}
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.text }}</div>
            <div class="message-meta">
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
              <button
                v-if="message.audioBase64 && message.type === 'ai'"
                :class="['play-btn', { playing: message.isPlaying }]"
                @click="playMessage(message)"
                :disabled="isPlaying"
              >
                {{ message.isPlaying ? '⏸️' : '🔊' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 处理中指示器 -->
        <div v-if="isProcessing" class="processing-indicator">
          <div class="ai-avatar">🤖</div>
          <div class="processing-text">
            <div class="typing-animation">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <p>{{ processingText }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <!-- 文本模式 -->
      <div v-if="!isVoiceMode" class="text-input-container">
        <div class="input-wrapper">
          <input
            v-model="textInput"
            type="text"
            placeholder="输入您的问题..."
            @keyup.enter="sendTextMessage"
            :disabled="isProcessing"
            class="text-input"
          />
          <button
            @click="sendTextMessage"
            :disabled="!textInput.trim() || isProcessing"
            class="send-btn"
          >
            {{ isProcessing ? '⏳' : '📤' }}
          </button>
        </div>
      </div>

      <!-- 语音模式 -->
      <div v-else class="voice-input-container">
        <div class="voice-controls">
          <button
            :class="['record-btn', { recording: recorder.state.isRecording, disabled: isProcessing }]"
            @click="toggleRecording"
            :disabled="isProcessing"
          >
            <span class="record-icon">
              {{ recorder.state.isRecording ? '⏹️' : '🎤' }}
            </span>
            <span class="record-text">
              {{ recorder.state.isRecording ? `录制中 ${recordingDuration}s` : '点击录音' }}
            </span>
          </button>
          
          <div v-if="recorder.state.isRecording" class="recording-indicator">
            <div class="sound-wave">
              <div class="wave"></div>
              <div class="wave"></div>
              <div class="wave"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 语音功能状态 -->
    <div class="voice-status">
      <span :class="['voice-indicator', { active: voiceSupported }]">
        {{ voiceSupported ? '✅ 语音功能已启用' : '❌ 语音功能不可用' }}
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { voiceChatApi, type VoiceChatRequest, type VoiceChatResponse } from '../services/api'
import { useAudioRecorder } from '../composables/useAudioRecorder'
import { useAudioPlayer } from '../composables/useAudioPlayer'

// 消息类型定义
interface ChatMessage {
  id: string
  type: 'user' | 'ai' | 'system'
  text: string
  audioBase64?: string
  timestamp: number
  isPlaying?: boolean
}

// 响应式状态
const messages = ref<ChatMessage[]>([])
const textInput = ref('')
const isVoiceMode = ref(false)
const isProcessing = ref(false)
const processingText = ref('正在处理...')
const isPlaying = ref(false)
const chatArea = ref<HTMLElement>()

// 录音相关状态
const recordingDuration = ref(0)
let recordingTimer: number | null = null

// 服务状态
const serviceStatus = ref<'online' | 'offline' | 'error'>('offline')
const serviceStatusText = computed(() => {
  switch (serviceStatus.value) {
    case 'online': return 'HTTP服务正常'
    case 'offline': return '服务离线'
    case 'error': return '服务异常'
    default: return '未知状态'
  }
})

// 使用组合式函数
const recorder = useAudioRecorder()
const player = useAudioPlayer()

// 语音功能检测
const voiceSupported = computed(() => {
  return recorder.isSupported && player.isSupported
})

// 生命周期
onMounted(async () => {
  console.log('HttpVoiceChat组件已挂载')
  console.log('录音支持:', recorder.isSupported)
  console.log('播放支持:', player.isSupported)
  console.log('语音功能支持:', voiceSupported.value)
  
  await checkServiceHealth()
  checkVoiceSupport()
  addSystemMessage('AI语音助手已启动，选择文本或语音模式开始对话')
})

onUnmounted(() => {
  if (recordingTimer) {
    clearInterval(recordingTimer)
  }
  recorder.cleanup()
  player.cleanup()
})

// 检查服务健康状态
const checkServiceHealth = async () => {
  try {
    await voiceChatApi.health()
    serviceStatus.value = 'online'
    console.log('HTTP服务健康检查通过')
  } catch (error) {
    console.error('HTTP服务健康检查失败:', error)
    serviceStatus.value = 'error'
  }
}

// 检查语音功能支持
const checkVoiceSupport = () => {
  if (voiceSupported.value) {
    addSystemMessage('✅ 语音功能已启用')
  } else {
    addSystemMessage('❌ 语音功能不可用，请使用文本模式')
    console.warn('语音功能不可用:', {
      recorder: recorder.isSupported,
      player: player.isSupported,
      mediaDevices: !!navigator.mediaDevices,
      getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
      MediaRecorder: !!window.MediaRecorder,
      Audio: !!window.Audio
    })
  }
}

// 模式切换
const setMode = (voice: boolean) => {
  isVoiceMode.value = voice
  console.log(`切换到${voice ? '语音' : '文本'}模式`)
}

// 添加消息
const addMessage = (type: 'user' | 'ai' | 'system', text: string, audioBase64?: string) => {
  const message: ChatMessage = {
    id: Date.now().toString(),
    type,
    text,
    audioBase64,
    timestamp: Date.now(),
    isPlaying: false
  }
  messages.value.push(message)
  nextTick(() => scrollToBottom())
  return message
}

const addUserMessage = (text: string) => addMessage('user', text)
const addAiMessage = (text: string, audioBase64?: string) => addMessage('ai', text, audioBase64)
const addSystemMessage = (text: string) => addMessage('system', text)

// 滚动到底部
const scrollToBottom = () => {
  if (chatArea.value) {
    chatArea.value.scrollTop = chatArea.value.scrollHeight
  }
}

// 时间格式化
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 发送文本消息
const sendTextMessage = async () => {
  const text = textInput.value.trim()
  if (!text || isProcessing.value) return

  console.log('发送文本消息:', text)
  addUserMessage(text)
  textInput.value = ''
  
  await processMessage({
    textInput: text,
    sessionId: Date.now().toString()
  })
}

// 录音控制
const toggleRecording = async () => {
  if (!voiceSupported.value || isProcessing.value) return

  if (recorder.state.isRecording) {
    await stopRecording()
  } else {
    await startRecording()
  }
}

const startRecording = async () => {
  try {
    const success = await recorder.startRecording()
    if (success) {
      recordingDuration.value = 0
      recordingTimer = setInterval(() => {
        recordingDuration.value++
      }, 1000)
      console.log('开始录音')
    } else {
      addSystemMessage('❌ 录音失败: ' + (recorder.state.error || '未知错误'))
    }
  } catch (error) {
    console.error('开始录音失败:', error)
    addSystemMessage('❌ 录音失败: ' + (error as Error).message)
  }
}

const stopRecording = async () => {
  try {
    if (recordingTimer) {
      clearInterval(recordingTimer)
      recordingTimer = null
    }

    const audioBlob = await recorder.stopRecording()
    if (audioBlob) {
      const audioBase64 = await blobToBase64(audioBlob)
      
      console.log('录音完成，时长:', recordingDuration.value + 's')
      addUserMessage(`🎤 语音消息 (${String(Math.floor(recordingDuration.value / 60)).padStart(2, '0')}:${String(recordingDuration.value % 60).padStart(2, '0')})`)
      
      await processMessage({
        audioBase64,
        sessionId: Date.now().toString()
      })
    } else {
      addSystemMessage('❌ 录音数据为空')
    }
  } catch (error) {
    console.error('停止录音失败:', error)
    addSystemMessage('❌ 录音处理失败: ' + (error as Error).message)
  }
}

// 处理消息（HTTP方式）
const processMessage = async (request: VoiceChatRequest) => {
  isProcessing.value = true
  processingText.value = '正在处理...'

  try {
    console.log('发送HTTP请求:', request)
    const response = await voiceChatApi.chat(request)
    console.log('收到HTTP响应:', response)
    
    handleVoiceResponse(response)
  } catch (error) {
    console.error('消息处理失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    addSystemMessage('❌ 处理失败: ' + errorMessage)
  } finally {
    isProcessing.value = false
  }
}

// 处理语音响应
const handleVoiceResponse = (response: VoiceChatResponse) => {
  if (response.status === 'success') {
    if (response.aiResponse) {
      const aiMessage = addAiMessage(response.aiResponse, response.audioBase64)
      
      // 语音模式下自动播放AI回复
      if (response.audioBase64 && isVoiceMode.value) {
        setTimeout(() => {
          playMessage(aiMessage)
        }, 500)
      }
    }
  } else {
    const errorMessage = response.errorMessage || '处理失败'
    addSystemMessage('❌ ' + errorMessage)
    console.error('语音响应错误:', response)
  }
}

// 播放消息音频
const playMessage = async (message: ChatMessage) => {
  if (!message.audioBase64 || isPlaying.value) return

  try {
    isPlaying.value = true
    message.isPlaying = true
    
    const success = await player.playBase64Audio(message.audioBase64)
    if (success) {
      console.log('音频播放完成')
    } else {
      addSystemMessage('❌ 音频播放失败')
    }
  } catch (error) {
    console.error('音频播放失败:', error)
    addSystemMessage('❌ 音频播放失败')
  } finally {
    isPlaying.value = false
    message.isPlaying = false
  }
}

// 工具函数
const blobToBase64 = (blob: Blob): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      const base64 = result.split(',')[1]
      resolve(base64)
    }
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}
</script>

<style scoped>
.http-voice-chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.service-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: white;
  font-size: 0.9rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.status-dot.online { background: #4ade80; }
.status-dot.offline { background: #6b7280; }
.status-dot.error { background: #ef4444; }

.mode-toggle {
  display: flex;
  gap: 0.5rem;
}

.mode-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.9rem;
}

.mode-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.mode-btn.active {
  background: white;
  color: #667eea;
  font-weight: 600;
}

/* 聊天区域 */
.chat-area {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  scroll-behavior: smooth;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.welcome-message {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 2rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  backdrop-filter: blur(10px);
  color: white;
  text-align: center;
}

.ai-avatar {
  font-size: 3rem;
  flex-shrink: 0;
}

.welcome-text h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.2rem;
}

.welcome-text p {
  margin: 0;
  opacity: 0.8;
  font-size: 0.9rem;
}

.message-item {
  display: flex;
  gap: 0.75rem;
  animation: slideIn 0.3s ease-out;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  flex-shrink: 0;
  background: rgba(255, 255, 255, 0.2);
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.user .message-content {
  align-self: flex-end;
}

.message-text {
  padding: 0.75rem 1rem;
  border-radius: 18px;
  line-height: 1.4;
  word-wrap: break-word;
}

.user .message-text {
  background: #667eea;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai .message-text {
  background: white;
  color: #333;
  border-bottom-left-radius: 4px;
}

.system .message-text {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 0.9rem;
  text-align: center;
  border-radius: 12px;
}

.message-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 0.25rem;
  font-size: 0.75rem;
  opacity: 0.7;
  color: white;
}

.play-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1rem;
  padding: 0.25rem;
  border-radius: 50%;
  transition: transform 0.2s;
}

.play-btn:hover {
  transform: scale(1.1);
}

.play-btn.playing {
  animation: pulse 1s infinite;
}

/* 处理指示器 */
.processing-indicator {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  color: white;
}

.typing-animation {
  display: flex;
  gap: 0.25rem;
  margin-bottom: 0.5rem;
}

.typing-animation span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-animation span:nth-child(2) { animation-delay: 0.2s; }
.typing-animation span:nth-child(3) { animation-delay: 0.4s; }

/* 输入区域 */
.input-area {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.input-wrapper {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.text-input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: none;
  border-radius: 25px;
  background: white;
  font-size: 1rem;
  outline: none;
}

.text-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 25px;
  background: #667eea;
  color: white;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s;
}

.send-btn:hover:not(:disabled) {
  background: #5a67d8;
  transform: translateY(-1px);
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 语音控制 */
.voice-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.record-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem;
  border: none;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 120px;
  min-height: 120px;
}

.record-btn:hover:not(.disabled) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.record-btn.recording {
  background: #ef4444;
  animation: pulse 1.5s infinite;
}

.record-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.record-icon {
  font-size: 2rem;
}

.record-text {
  font-size: 0.9rem;
  text-align: center;
}

/* 录音指示器 */
.recording-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.sound-wave {
  display: flex;
  gap: 2px;
  align-items: center;
}

.wave {
  width: 3px;
  height: 20px;
  background: white;
  border-radius: 2px;
  animation: wave 1s infinite ease-in-out;
}

.wave:nth-child(2) { animation-delay: 0.1s; }
.wave:nth-child(3) { animation-delay: 0.2s; }

/* 语音状态 */
.voice-status {
  padding: 0.5rem 1rem;
  text-align: center;
  background: rgba(0, 0, 0, 0.1);
  font-size: 0.8rem;
}

.voice-indicator {
  color: rgba(255, 255, 255, 0.8);
}

.voice-indicator.active {
  color: #4ade80;
}

/* 动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

@keyframes typing {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-10px); }
}

@keyframes wave {
  0%, 40%, 100% { transform: scaleY(0.4); }
  20% { transform: scaleY(1); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .http-voice-chat {
    height: 100vh;
  }
  
  .status-bar {
    padding: 0.75rem;
  }
  
  .chat-area {
    padding: 0.75rem;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .record-btn {
    min-width: 100px;
    min-height: 100px;
  }
}
</style>